<template>
  <div class="cardArea">
    <!-- 密码头像区域 -->
    <div class="personalArea">
      <div class="personalArea_avatar">
        <a-avatar v-if="currentUser.avatar" size="default" :src="currentUser.avatar" class="defaultAvatar" />
        <img v-else src="@/assets/images/defaultAva.png" alt="" class="defaultAvatar" />
        <span class="personalArea_avatar_txt">{{ currentUser.fullname }}</span>
      </div>
      <!-- 密码表单区域 -->
      <div class="personalArea_info">
        <a-form-model class="personalArea_info_form" ref="modifyForm" :rules="rulesPassword" :model="modifyForm"
          :forceRender="true">
          <template>
            <div>
              <div class="validity" v-if="timeoutDays() >= 30">
                <a-icon type="check-circle" style="color: blue" /> 密码有效期至{{ userData.expireddate }}
              </div>
              <div class="remainingdate" v-else-if="timeoutDays() > 0 && timeoutDays() < 30">
                <a-icon type="exclamation-circle" style="color: rgb(252, 185, 3)" /> 密码有效期还剩{{
                  timeoutDays()
                }}天，请及时修改
              </div>
              <div class="expired" v-else-if="timeoutDays() <= 0">
                <a-icon type="exclamation-circle" style="color: rgb(230, 14, 14)" /> 密码已过期，请及时修改
              </div>
            </div>
          </template>
          <!-- 新密码 -->
          <a-form-model-item label="新密码" prop="onwPassWord" :label-col="labelCol" :wrapper-col="wrapperCol" has-feedback>
            <a-input v-model="modifyForm.onwPassWord" @change="passWordChange" :maxLength="16" autocomplete="off"
              placeholder="密码由8 ~ 16位的字母、数字、特殊字符组成" />
          </a-form-model-item>
          <!-- 确认密码 -->
          <a-form-model-item prop="twoPassWord" label="确认密码" :label-col="labelCol" :wrapper-col="wrapperCol" has-feedback>
            <a-input v-model="modifyForm.twoPassWord" :maxLength="16" autocomplete="off" placeholder="请再次输入密码" />
          </a-form-model-item>
        </a-form-model>
      </div>
    </div>
    <div class="personalArea_info_button">
      <a-button @click="onSubmit()" :loading="loading"> 保存 </a-button>
    </div>
  </div>
</template>
<script>
import storage from 'store'
import { updatePassword, ssoLogout } from '@/api/sso.js'
import { ACCESS_TOKEN, APP_USER, APP_DEPT } from '@/store/mutation-types'
import { viewHa_user } from '@/api/base/ha_user'
export default {
  data() {
    return {
      modifyForm: {
        onwPassWord: '', // 修改密码
        twoPassWord: '', // 确认密码
      },
      currentUser: storage.get(APP_USER),
      userData: {}, //保存用户数据的变量
      labelCol: { span: 2 }, // label宽
      wrapperCol: { span: 8 }, // 组件宽
      // 密码校验规则
      rulesPassword: {
        onwPassWord: [{ required: true, message: '请输入新密码', trigger: ['blur', 'change'] }],
        twoPassWord: [{ required: true, message: '请再次输入密码', trigger: ['blur', 'change'] }],
      },
      currentUser: storage.get(APP_USER), // 用户信息
      loading: false, //按钮显示
    }
  },
  async created() {
    this.fetchUserData()
  },
  methods: {
    checkPassWord(newpass) {
      if (newpass.indexOf(' ') != -1) {
        this.$message.warning('密码不能含有空格')
        return 0
      }
      if (newpass.length < 8) {
        this.$message.warning('请输入8 ~ 16位的字母、数字、特殊字符')
        return 0
      }
      var checkNum = 0
      //是否包含小写字母
      if (newpass.match(/([a-z])+/)) {
        checkNum++
      }
      //是否包含数字
      if (newpass.match(/([0-9])+/)) {
        checkNum++
      }
      //是否包含大写字母
      if (newpass.match(/([A-Z])+/)) {
        checkNum++
      }
      //是否包含特殊字符
      if (newpass.match(/[^a-zA-Z0-9]+/)) {
        checkNum++
      }
      if (checkNum < 3) {
        this.$message.warning('密码必须包含大写/小写/数字/符号其中至少3种组合, 8位长度或以上')
      }
      return checkNum
    },
    fetchUserData() {
      viewHa_user(this.currentUser.userId).then((res) => {
        this.userData = res.data
        console.log('data', res.data)
      })
    },

    timeoutDays() {
      if (this.formatDate() && this.userData.expireddate) {
        const formatDateStr = (dateStr) => {
          const [year, month, day] = dateStr.split('-').map(Number)
          return new Date(year, month - 1, day)
        }

        const date1 = formatDateStr(this.formatDate())
        const date2 = formatDateStr(this.userData.expireddate)

        const diffTime = date2.getTime() - date1.getTime()
        const diffDays = Math.ceil(diffTime / (1000 * 3600 * 24))

        return diffDays
      } else {
        // 如果日期不可用，返回一个默认值或者进行其他处理
        return 0;
      }
    },

    //创新日期
    formatDate() {
      const date = new Date()
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')

      return `${year}-${month}-${day}`
    },
    // 提交表单
    onSubmit() {
      this.loading = true
      this.$refs.modifyForm.validate((valid) => {
        if (valid) {
          if (this.checkPassWord(this.modifyForm.onwPassWord) < 3) {
            this.loading = false
            return false
          } else if (this.modifyForm.onwPassWord != this.modifyForm.twoPassWord) {
            this.loading = false
            this.$message.warning('两次输入的密码不一致')
            return false
          } else {
            updatePassword({
              newPassword: this.modifyForm.onwPassWord,
            })
              .then((res) => {
                console.log('修改密码', res.code)
                if (res.code !== 200) {
                  this.$message.error('修改失败')
                } else {
                  this.$message.success('修改成功')
                  // 如果修改的是自己的密码退出登录
                  setTimeout(async () => {
                    let resLogout = await ssoLogout()
                    if (resLogout.code == 200) {
                      // 清除token信息
                      storage.remove(ACCESS_TOKEN)
                      // 清除用户信息
                      storage.remove(APP_USER)
                      storage.remove(APP_DEPT)
                      this.$router.push({ path: '/index' })
                    }
                  }, 500)
                }
              })
              .finally(() => {
                this.loading = false
              })
          }
        } else {
          this.loading = false
        }
      })
    },
    // 密码改变
    passWordChange(e) {
      // 匹配到中文的下标
      let regular = /[\u4e00-\u9fa5]/
      if (regular.test(this.modifyForm.onwPassWord)) {
        const index = this.modifyForm.onwPassWord.match(regular).index
        this.modifyForm.onwPassWord = this.modifyForm.onwPassWord.substring(0, index)
      }
      // 匹配到中文符号的下标
      let regular2 =
        /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/
      if (regular2.test(this.modifyForm.onwPassWord)) {
        const index2 = this.modifyForm.onwPassWord.match(regular2).index
        this.modifyForm.onwPassWord = this.modifyForm.onwPassWord.substring(0, index2)
      }
    },
  },
}
</script>

<style lang="less" scoped>
.validity {
  position: relative;
  top: 40%;
  left: 63%;
  transform: translate(-50%, -50%) translateX(-50px);
  color: rgb(9, 9, 228);
}

.remainingdate {
  position: relative;
  top: 40%;
  left: 63%;
  transform: translate(-50%, -50%) translateX(-50px);
  color: rgb(252, 185, 3);
}

.expired {
  position: relative;
  top: 40%;
  left: 63%;
  transform: translate(-50%, -50%) translateX(-50px);
  color: rgb(230, 14, 14);
}

/deep/ .ant-form-item label {
  color: #adadae;
}

.cardArea {
  background-color: #fff;
  min-height: 700px;
}

.personalArea {
  padding: 55px;
}

.personalArea_avatar {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.personalArea_avatar_img {
  border-radius: 50%;
  width: 80px;
  object-fit: cover;
  border: 1px solid #f5f5f5;
}

.personalArea_avatar_txt {
  margin-top: 10px;
  font-weight: 550;
  font-size: 18px;
}

.personalArea_info {
  margin-top: 65px;
  margin-left: 36%;
}

.personalArea_info_form {
  padding: 27px 0;
}

.personalArea_info_button {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-bottom: 80px;
}

/deep/.ant-btn {
  background-color: #65b4fe;
  color: #ffffff;
}

.defaultAvatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}
</style>
